﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using EvincePayroll.Data;
using EvincePayroll.Utility;
using System.Text;
using System.Configuration;
using System.Net.Mail;
using System.Net;
using EvinceUI;
using EvinceUI.JQueryDataTable.Model;


namespace EvincePayroll.Controllers
{
    public class UserRoleController : Controller
    {
        //
        // GET: /UserRole/
        [Authorize.SessionExpire]
        public ActionResult Role()
        {
            return View();

        }
        [Authorize.SessionExpire]
        public PartialViewResult _CreateRole()
        {
            return PartialView();
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public PartialViewResult _CreateRole(string RoleName)
        {
            bool result = false;
            var emailId = Session["EmployeeData"] as EmployeeData;
            EvincePayrollService userRoleService = new EvincePayrollService(ServiceTypes.UserRole);
            if (RoleName != null)
            {
                result = userRoleService.CreateRole(emailId.Email, RoleName);


            }

            return PartialView("Role");
        }
        [Authorize.SessionExpire]
        public PartialViewResult _ShowRole()
        {

            return PartialView();
        }
        [Authorize.SessionExpire]
        public ActionResult AjaxShowRole(JQueryDataTableParamModel param)
        {
            List<UserRoleData> userRole;
            EmployeeData employee = (EmployeeData)Session["EmployeeData"];
            EvincePayrollService userRoleService = new EvincePayrollService(ServiceTypes.UserRole);
            userRole = userRoleService.GetAllUserRole(employee.Email);
            if (userRole != null)
            {
                IEnumerable<UserRoleData> filteredRequests;

                //Check whether the companies should be filtered by keyword
                if (!string.IsNullOrEmpty(param.sSearch))
                {
                    //Used if particular columns are filtered


                    var RoleNameFilter = Convert.ToString(Request["sSearch_1"]);

                    //Optionally check whether the columns are searchable at all

                    var RoleNameSearchable = Convert.ToBoolean(Request["bSearchable_1"]);

                    char[] chars = new char[] { '&', '|' };

                    if (param.sSearch.IndexOfAny(chars) > 0)
                    {
                        string expression = GetExpression(param.sSearch.ToUpper());
                        StringBuilder filter = new StringBuilder();
                        filter.Append("(").Append(expression.Replace("[FIELD]", "RoleName.ToUpper()")).Append(") ||");


                        filteredRequests = userRole;
                    }
                    else
                    {

                        filteredRequests = userRole
                        .Where(d => RoleNameSearchable && d.UserRole.Contains(param.sSearch.Trim().ToLower())
                        );

                    }
                }
                else
                {
                    filteredRequests = userRole;

                }

                var roleNameTitle = Convert.ToBoolean(Request["bSortable_1"]);






                var sortColumnIndex = Convert.ToInt32(Request["iSortCol_0"]);
                Func<UserRoleData, string> orderingFunction = (//d => sortColumnIndex == 1 && isEmployeeId ? d.EmployeeStringId.ToString() :
               d => sortColumnIndex == 1 && roleNameTitle ? d.UserRole.ToString() :

                "");

                var sortDirection = Request["sSortDir_0"]; // asc or desc
                if (sortDirection == "asc")
                    filteredRequests = filteredRequests.OrderBy(orderingFunction);
                else
                    filteredRequests = filteredRequests.OrderByDescending(orderingFunction);

                var displayedCompanies = filteredRequests.Skip(param.iDisplayStart).Take(param.iDisplayLength);
                var result = from p in displayedCompanies
                             select new[] {
                            p.UserRoleId.ToString(),
                            p.UserRole,
                            DeleteRoleLink(p.UserRoleId.ToString())
                           
                           
                         };

                return Json(new
                {
                    sEcho = param.sEcho,
                    iTotalRecords = userRole.Count(),
                    iTotalDisplayRecords = filteredRequests.Count(),
                    aaData = result
                },
                JsonRequestBehavior.AllowGet);
            }
            else
                return Json(new { }, JsonRequestBehavior.AllowGet);
        }
        [Authorize.SessionExpire]
        private string GetExpression(string p)
        {
            throw new NotImplementedException();
        }
        [Authorize.SessionExpire]
        public string DeleteRoleLink(string userId)
        {
            string url = string.Empty;
            url = string.Format("<a href=\"#\" onclick=\"DeleteRole('{0}')\">Delete</a>", userId);
            return url;
        }
        [Authorize.SessionExpire]
        public ActionResult DeleteRole(string userId)
        {
            bool result = false;
            Guid UserId;
            UserId = new Guid(userId);
            if (UserId != null)
            {
                EmployeeData employee = (EmployeeData)Session["EmployeeData"];
                EvincePayrollService userRoleService = new EvincePayrollService(ServiceTypes.UserRole);
                result = userRoleService.DeleteRole(userId);


            }
            return Json(new { result }, JsonRequestBehavior.AllowGet);

        }
        [Authorize.SessionExpire]
        public ActionResult UserRoleManager()
        {
            EmployeeData employee = (EmployeeData)Session["EmployeeData"];
            EvincePayrollService userRoleService = new EvincePayrollService(ServiceTypes.UserRole);
            ViewBag.UserRoleList = userRoleService.GetUserRoleList(employee.Email);
            return View();
        }
        [Authorize.SessionExpire]
        public PartialViewResult _UserRoleManagerTable(string roleId)
        {
            ViewBag.UserRoleId = roleId;
            return PartialView();
        }


        [Authorize.SessionExpire]
        public ActionResult AjaxGetUserRoleManager(JQueryDataTableParamModel param, string roleId)
        {
            List<MenuTableData> menuTableList;
            EmployeeData employee = (EmployeeData)Session["EmployeeData"];
            EvincePayrollService userRoleService = new EvincePayrollService(ServiceTypes.Account);
            menuTableList = userRoleService.GetMenuList(employee.Email, roleId);
            if (menuTableList != null)
            {
                IEnumerable<MenuTableData> filteredRequests;

                //Check whether the companies should be filtered by keyword
                if (!string.IsNullOrEmpty(param.sSearch))
                {
                    //Used if particular columns are filtered


                    var menuNameFilter = Convert.ToString(Request["sSearch_1"]);
                    var menuTitleFilter = Convert.ToString(Request["sSearch_3"]);




                    //Optionally check whether the columns are searchable at all


                    var ismenuNameSearchable = Convert.ToBoolean(Request["bSearchable_1"]);
                    var ismenuTitleSearchable = Convert.ToBoolean(Request["bSearchable_3"]);




                    char[] chars = new char[] { '&', '|' };

                    if (param.sSearch.IndexOfAny(chars) > 0)
                    {
                        string expression = GetExpression(param.sSearch.ToUpper());
                        StringBuilder filter = new StringBuilder();

                        filter.Append("(").Append(expression.Replace("[FIELD]", "MenuName.ToString().ToUpper()")).Append(")||");
                        filter.Append("(").Append(expression.Replace("[FIELD]", "Title.ToString().ToUpper()")).Append(")");
                        filteredRequests = menuTableList;
                    }
                    else
                    {

                        filteredRequests = menuTableList
                        .Where(d => ismenuNameSearchable && d.MenuName.ToLower().Contains(param.sSearch.Trim().ToLower())
                        ||
                        ismenuTitleSearchable && d.Title.ToString().ToLower().Contains(param.sSearch.Trim().ToLower())

                        );

                    }
                }
                else
                {
                    filteredRequests = menuTableList;

                }


                var isMenuName = Convert.ToBoolean(Request["bSortable_1"]);
                var isMenuTitle = Convert.ToBoolean(Request["bSortable_3"]);



                var sortColumnIndex = Convert.ToInt32(Request["iSortCol_0"]);
                Func<MenuTableData, string> orderingFunction = (d => sortColumnIndex == 1 && isMenuName ? d.MenuName :

                sortColumnIndex == 3 && isMenuTitle ? d.Title.ToString() :
                "");

                var sortDirection = Request["sSortDir_0"]; // asc or desc
                if (sortDirection == "asc")
                    filteredRequests = filteredRequests.OrderBy(orderingFunction);
                else
                    filteredRequests = filteredRequests.OrderByDescending(orderingFunction);

                var displayedCompanies = filteredRequests.Skip(param.iDisplayStart).Take(param.iDisplayLength);
                var result = from p in displayedCompanies
                             select new[] {
                             p.MenuId.ToString(),
                             p.MenuName,
                             p.URL,
                             p.Title,
                             p.Description,
                             GetParentMenuName(menuTableList,p.ParentId),
                             GetParentList(menuTableList,p.ParentId,p.MenuId),
                             GetDisplayOrderNumber(p.MenuId,p.DisplayOrder),
                             MenuCheckBox(p.MenuId.ToString(),p.isChecked)

                             
                             
                             //string.Format("<a href=\"#\" onclick=\"updateStatusAccept(this,{2},'{3}','{4}')\" id=\"{0}\" class=\"ApproveStatus\">Approve<input type=\"hidden\" value=\"{1}\" /></a>",Convert.ToString(p.LeaveId),Convert.ToString(p.LeaveId),GetDays(p.FromDate,p.ToDate),Convert.ToString(p.FromDate),p.LeaveId)+" / "+
                             //string.Format("<a href=\"#\" onclick=\"updateStatusReject(this,'{2}')\" id=\"{0}\" class=\"RejectStatus\">Reject<input type=\"hidden\" value=\"{1}\" /></a>",Convert.ToString(p.LeaveId),Convert.ToString(p.LeaveId),p.LeaveId)
                         };

                return Json(new
                {
                    sEcho = param.sEcho,
                    iTotalRecords = menuTableList.Count(),
                    iTotalDisplayRecords = filteredRequests.Count(),
                    aaData = result
                },
                JsonRequestBehavior.AllowGet);
            }
            else
                return Json(new { }, JsonRequestBehavior.AllowGet);
        }
        [Authorize.SessionExpire]
        public string GetDisplayOrderNumber(Guid menuId, Int32 displayOrder)
        {
            string result = string.Format("<input type=\"text\" style=\"width:30px;\" id=\"Sort_{0}\" value=\"{1}\" />", menuId, displayOrder);
            return result;
        }
        [Authorize.SessionExpire]
        public string GetParentMenuName(List<MenuTableData> menuList, string parentId)
        {
            string result = string.Empty;
            var parentMenu = menuList.Where(x => x.MenuId.ToString().Equals(parentId)).FirstOrDefault();
            if (parentMenu != null)
                result = string.Format("<label style=\"color:Orange\">{0}</label>", parentMenu.Title);
            else
                result = "<label style=\"color:Green\">Root Menu</label>";
            return result;
        }
        [Authorize.SessionExpire]
        public string GetParentList(List<MenuTableData> menuList, string parentId, Guid menuId)
        {
            string result = string.Empty;
            result += string.Format("<select id=\"Select_{0}\">", menuId);
            foreach (var i in menuList)
            {
                if (i.MenuId.Equals(Constants.ROOT_NODE))
                    result += string.Format("<option value=\"{0}\" selected=\"selected\">{1}</option>", i.MenuId, i.Title);
                else
                    result += string.Format("<option value=\"{0}\" >{1}</option>", i.MenuId, i.Title);
            }
            result += "</select>";
            return result;
        }
        [Authorize.SessionExpire]
        public string MenuCheckBox(string menuId, bool isChecked)
        {
            string url = string.Empty;
            //url = string.Format(" <a onclick=\"updateMenu({1})\" href=\"#\"><input onclick=\"updateMenu({1})\" type=\"checkbox\" id=\"{0}\" class=\"chkBox\"/></a>", menuId, menuId);
            //checked="checked"
            if (isChecked == true)
                url = string.Format("<input checked=\"checked\" type=\"checkbox\" id=\"CHK_{0}\" class=\"chkBox\"/>  <a href=\"#\" onclick=\"updateMenu('{1}')\" id=\"Update_{2}\">Update</a>", menuId, menuId, menuId);
            else
                url = string.Format("<input type=\"checkbox\" id=\"CHK_{0}\" class=\"chkBox\"/>  <a href=\"#\" onclick=\"updateMenu('{1}')\" id=\"Update_{2}\">Update</a>", menuId, menuId, menuId);
            return url;
        }
        [Authorize.SessionExpire]
        public ActionResult UpdateRoleAccess(string menuId, string roleId, string sortOrder, string parentId)
        {
            bool result;
            if (roleId != null && menuId != null)
            {
                EmployeeData employee = (EmployeeData)Session["EmployeeData"];
                EvincePayrollService userRoleService = new EvincePayrollService(ServiceTypes.UserRole);

                result = userRoleService.UpdateRoleAccess(menuId, roleId, sortOrder, parentId);
            }
            return Json(new { }, JsonRequestBehavior.AllowGet);
        }
        [Authorize.SessionExpire]
        public ActionResult DeleteRoleAccess(string menuId, string roleId)
        {
            bool result;
            if (roleId != null && menuId != null)
            {
                EmployeeData employee = (EmployeeData)Session["EmployeeData"];
                EvincePayrollService userRoleService = new EvincePayrollService(ServiceTypes.UserRole);

                result = userRoleService.DeleteRoleAccess(menuId, roleId);

            }
            return Json(new { }, JsonRequestBehavior.AllowGet);

        }
        [Authorize.SessionExpire]
        public PartialViewResult _DynamicNavigation()
        {
            var employeeData = Session["EmployeeData"];
            EvincePayrollService accountService = new EvincePayrollService(ServiceTypes.Account);
            List<DynamicMenu> menuList = accountService.DynamicMenu(employeeData as EmployeeData);
            // string _HTML = GetMenu(menuList,Constants.ROOT_NODE);


            ViewBag.Menu = menuList;
            ViewBag.UserData = employeeData as EmployeeData;
            return PartialView();
        }




        [Authorize.SessionExpire]
        public ActionResult ManageMenu()
        {


            return View();
        }
        [Authorize.SessionExpire]
        public PartialViewResult _CreateMenu()
        {


            return PartialView();
        }

        [Authorize.SessionExpire]
        public ActionResult CreateNewMenu(MenuTableData menuTableData, string isActive)
        {
            EvincePayrollService accountService = new EvincePayrollService(ServiceTypes.Account);
            bool result = false;
            if (menuTableData != null)
            {
                if (isActive == "true")
                {
                    EmployeeData employee = (EmployeeData)Session["EmployeeData"];
                    menuTableData.IsActive = true;


                    
                    result = accountService.CreateMenuList(menuTableData, employee.Email);
                }
                else if (isActive == "false")
                {
                    EmployeeData employee = (EmployeeData)Session["EmployeeData"];
                    menuTableData.IsActive = false;


                    result = accountService.CreateMenuList(menuTableData, employee.Email);
                }

            }


            return Json(new { Result = "Success" }, JsonRequestBehavior.AllowGet);
        }
        [Authorize.SessionExpire]
        public PartialViewResult _ShowMenu()
        {

            return PartialView();
        }
        [Authorize.SessionExpire]
        public ActionResult AjaxGetShowMenu(JQueryDataTableParamModel param)
        {
            List<MenuTableData> menuTableData;
            EmployeeData employee = (EmployeeData)Session["EmployeeData"];
            EvincePayrollService accountService = new EvincePayrollService(ServiceTypes.Account);
            menuTableData = accountService.GetMenuList(employee.Email,string.Empty);
            if (menuTableData != null)
            {
                IEnumerable<MenuTableData> filteredRequests;

                //Check whether the companies should be filtered by keyword
                if (!string.IsNullOrEmpty(param.sSearch))
                {
                    //Used if particular columns are filtered


                    var MenuNameFilter = Convert.ToString(Request["sSearch_1"]);
                    //var MetaKeywordFilter = Convert.ToString(Request["sSearch_3"]);









                    //Optionally check whether the columns are searchable at all

                    var isMenuNameSearchable = Convert.ToBoolean(Request["bSearchable_1"]);
                    //var isMetaKeyword = Convert.ToBoolean(Request["bSearchable_3"]);





                    char[] chars = new char[] { '&', '|' };

                    if (param.sSearch.IndexOfAny(chars) > 0)
                    {
                        string expression = GetExpression(param.sSearch.ToUpper());
                        StringBuilder filter = new StringBuilder();
                        filter.Append("(").Append(expression.Replace("[FIELD]", "MenuName.ToUpper()")).Append(") ||");
                        //filter.Append("(").Append(expression.Replace("[FIELD]", "MetaKeywords.ToString().ToUpper()")).Append(")||");

                        filteredRequests = menuTableData;
                    }
                    else
                    {

                        filteredRequests = menuTableData
                        .Where(d => isMenuNameSearchable && d.MenuName.ToString().Contains(param.sSearch.Trim().ToLower())
                        


                        );

                    }
                }
                else
                {
                    filteredRequests = menuTableData;

                }

                var isMenuNametitle = Convert.ToBoolean(Request["bSortable_1"]);
                //var isMetaKeywordtitle = Convert.ToBoolean(Request["bSortable_3"]);
                //var isMetaDescription = Convert.ToBoolean(Request["bSortable_4"]);





                var sortColumnIndex = Convert.ToInt32(Request["iSortCol_0"]);
                Func<MenuTableData, string> orderingFunction = (//d => sortColumnIndex == 1 && isEmployeeId ? d.EmployeeStringId.ToString() :
               d => sortColumnIndex == 1 && isMenuNametitle ? d.MenuName.ToString() :
                

                "");

                var sortDirection = Request["sSortDir_0"]; // asc or desc
                if (sortDirection == "asc")
                    filteredRequests = filteredRequests.OrderBy(orderingFunction);
                else
                    filteredRequests = filteredRequests.OrderByDescending(orderingFunction);

                var displayedCompanies = filteredRequests.Skip(param.iDisplayStart).Take(param.iDisplayLength);
                var result = from p in displayedCompanies
                             select new[] {
                            p.MenuId.ToString(),
                            p.MenuName,
                            p.URL,
                            p.Title,
                            p.Description,
                            MenuDeleteLink(p.MenuId.ToString())
                            
                            //GetStatus(p.Status.ToString()),
                           // GetEditPage(p.PageId.ToString())
                             
                            // string.Format("<a href=\"#\" onclick=\"updateStatusAccept(this)\" class=\"ApproveStatus\">Approve<input type=\"hidden\" value=\"{0}\" /></a>",Convert.ToString(p.LeaveId))+"/"+
                             //string.Format("<a href=\"#\" onclick=\"updateStatusReject(this)\" class=\"RejectStatus\">Reject<input type=\"hidden\" value=\"{0}\" /></a>",Convert.ToString(p.LeaveId))
                         };

                return Json(new
                {
                    sEcho = param.sEcho,
                    iTotalRecords = menuTableData.Count(),
                    iTotalDisplayRecords = filteredRequests.Count(),
                    aaData = result
                },
                JsonRequestBehavior.AllowGet);
            }
            else
                return Json(new { }, JsonRequestBehavior.AllowGet);
        }
        [Authorize.SessionExpire]
        public ActionResult DeleteMenu(string menuId)
        {
            bool result = false;
            if (menuId != null)
            {
                EvincePayrollService accountService = new EvincePayrollService(ServiceTypes.Account);

                result = accountService.DeleteMenu(menuId);
            
            }
            return Json(new { }, JsonRequestBehavior.AllowGet);
        }
        [Authorize.SessionExpire]
        public string MenuDeleteLink(string menuId)
        {
            string url = string.Empty;
            //url = string.Format(" <a onclick=\"updateMenu({1})\" href=\"#\"><input onclick=\"updateMenu({1})\" type=\"checkbox\" id=\"{0}\" class=\"chkBox\"/></a>", menuId, menuId);
            url = string.Format("<a href=\"#\" onclick=\"DeleteMenu('{0}')\" ><span>Delete</span></a>", menuId);
            return url;
        }

    }


}

